package com.huilian.tool.weixin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.common.config.WxOpenConfig;
import com.huilian.tool.common.utils.*;
import com.huilian.tool.weixin.enums.EventTypeEnum;
import com.huilian.tool.weixin.enums.MessageTypeEnum;
import com.huilian.tool.weixin.exception.WxServiceException;
import com.huilian.tool.weixin.service.WeiXinMsgEventService;
import com.huilian.tool.weixin.service.WeixinOpenService;
import com.huilian.tool.weixin.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 谢洛涛
 * @date 2023/3/29 11:15
 */
@Slf4j
@Service
public class WeixinOpenServiceImpl implements WeixinOpenService {
    @Autowired
    private WxOpenConfig wxOpenConfig;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;
    @Resource
    private WeiXinMsgEventService weiXinMsgEventService;
    private String COMPONENT_VERIFY_TICKET = "weixin_component_verify_yicket";






    /**
     * 开放平台授权事件接收配置
     */
    @Override
    public String getWxOpenTicket(HttpServletRequest request) throws DocumentException, AesException, IOException {
        Map<String, String> map = MessageUtil.xmlToMapTicket(request, wxOpenConfig);
        String componentVerifyTicket = map.get("ComponentVerifyTicket");
        if (!StringUtils.isEmpty(componentVerifyTicket)) {
            log.info("接收到开放平台 {} 回调ticket", componentVerifyTicket);
            redisCacheTemplate.opsForValue().set(COMPONENT_VERIFY_TICKET + "_" + wxOpenConfig.getComponentAppId(), componentVerifyTicket);
        }
        log.info("接收到开放平台 {} 回调ticket", wxOpenConfig.getComponentAppId());
        return "success";
    }

    @Override
    public String messageManage(HttpServletRequest request, String appId) throws DocumentException, AesException, IOException {
        Map<String, String> map = MessageUtil.xmlToMapTicket(request, wxOpenConfig);

        String msgType = map.get("MsgType");
        if (appId != null) {
            map.put("appId", appId);
        }

        String message = null;
        System.err.println(map);

        //事件处理
        String ticket = map.get("Ticket");
        String event = map.get("Event");
        if (!StringUtils.isEmpty(event)) {
            if (EventTypeEnum.SUBSCRIBE.getCode().equals(event) && !StringUtils.isEmpty(ticket)) {
                //用户未关注，扫带参数二维码事件
                message = weiXinMsgEventService.noSubscribeScanService(map);
            }  else if (EventTypeEnum.UNSUBSCRIBE.getCode().equals(event)) {
                //用户取关事件
                message = weiXinMsgEventService.unsubscribeService(map);
            } else if (EventTypeEnum.SCAN.getCode().equals(event)) {
                //用户已关注，扫码带参数二维码
                message = weiXinMsgEventService.subscribeScanService(map);
            } else if (EventTypeEnum.LOCATION.getCode().equals(event)) {
                //用户上报地址位置事件
                message = weiXinMsgEventService.locationEventService(map);
            } else if (EventTypeEnum.CLICK.getCode().equals(event)) {
                //自定义菜单点击事件
                message = weiXinMsgEventService.clickMenuService(map);
            } else if (EventTypeEnum.VIEW.getCode().equals(event)) {
                //点击菜单跳转链接时的事件推送
                message = weiXinMsgEventService.viewService(map);
            } else {
                log.error("未知事件:{}", map);
            }
        } else {
            if (MessageTypeEnum.TEXT.getCode().equals(msgType)) {
                //文本信息
                message = weiXinMsgEventService.textMsgService(map);
            } else if (MessageTypeEnum.IMAGE.getCode().equals(msgType)) {
                //图片信息
                message = weiXinMsgEventService.imageMsgService(map);
            } else if (MessageTypeEnum.VOICE.getCode().equals(msgType)) {
                //语音消息
                message = weiXinMsgEventService.voiceMsgService(map);
            } else if (MessageTypeEnum.VIDEO.getCode().equals(msgType)) {
                //视频消息
                message = weiXinMsgEventService.videoMsgService(map);
            } else if (MessageTypeEnum.SHORT_VIDEO.getCode().equals(msgType)) {
                //小视频消息
                message = weiXinMsgEventService.shortVideoMsgService(map);
            } else if (MessageTypeEnum.LOCATION.getCode().equals(msgType)) {
                //地址位置消息
                message = weiXinMsgEventService.locationMsgService(map);
            } else if (MessageTypeEnum.LINK.getCode().equals(msgType)) {
                //链接消息
                message = weiXinMsgEventService.linkMsgService(map);
            } else {
                log.error("未知消息:{}", map);
            }
        }

        String timeStamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");

        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(wxOpenConfig.getComponentToken(), wxOpenConfig.getComponentAesKey(), wxOpenConfig.getComponentAppId());
        if (StringUtils.isEmpty(message)) {
            message = "";
        }
        return wxBizMsgCrypt.encryptMsg(message, timeStamp, nonce, wxOpenConfig.getComponentAppId(), wxOpenConfig.getComponentToken());
    }


}
